import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';

import RegionIconSelect from './RegionIconSelect';
import {validatePhone, handlePhone} from 'WE/Utils';
import {Input, TouchableOpacity} from 'M/UI/Libraries';

const COUNTDOWN = 70;

export default class PhoneCaptcha extends Component {
  count = 60;

  constructor(props) {
    super(props);
    const {style, phone = '', name = '', value = ''} = props;
    this.style = style || styles;
    this.state = {
      showCountDown: false,
      countDown: COUNTDOWN,
      second: this.count,
      value,
      phone,
      name,
      region: {
        code: '86',
      },
    };
  }

  setPhone = text => {
    this.setState({phone: text});
  };
  setCode = text => {
    const {onSetCode = ({}) => {}} = this.props;
    this.setState({code: text});
    onSetCode({code: text});
  };
  onChangeRegion = item => {
    const phone = handlePhone(this.state.phone, this._input, item);
    this.setState({
      region: item,
      phone,
    });
  };

  renderInput = () => {
    const {region} = this.state;
    const {title: {phoneText = '请输入手机号'} = {}} = this.props;
    return (
      <View style={[this.style.inputContainer]}>
        <Input
          ref={ref => (this._input = ref)}
          inputContainerStyle={this.style.loginStyle.commonInputContainer}
          maxLength={15}
          inputStyle={[this.style.loginStyle.inputStyle, {paddingLeft: 15}]}
          leftIcon={
            <RegionIconSelect
              region={region}
              navigation={this.props.navigation}
              paddingLeft={0}
              onChangeRegion={this.onChangeRegion}
            />
          }
          leftIconContainerStyle={{marginLeft: 0}}
          placeholder={phoneText}
          placeholderTextColor={this.style.minorFontColor}
          onChangeText={this.setPhone}
          selectionColor={this.style.themeStyle.primaryColor}
          value={this.state.phone}
          phoneRegion={region}
          inputType="phone"
        />
      </View>
    );
  };
  setName = text => {
    const {onSetName = ({}) => {}} = this.props;
    this.setState({name: text});
    onSetName({name: text});
  };
  renderNameInput = () => {
    const {region} = this.state;
    const {title: {nameText = '请输入用户名'} = {}} = this.props;
    return (
      <View style={[this.style.inputContainer]}>
        <Input
          ref={ref => (this._input = ref)}
          maxLength={15}
          minLength={4}
          placeholder={nameText}
          inputContainerStyle={this.style.commonInputContainer}
          inputStyle={[this.style.loginStyle.inputStyle, {paddingLeft: 0}]}
          placeholderTextColor={this.style.themeStyle.minorFontColor}
          selectionColor={this.style.themeStyle.primaryColor}
          onChangeText={this.setName}
          value={this.state.name}
          phoneRegion={region}
        />
      </View>
    );
  };

  onSendCode = () => {
    const {isSend, region} = this.state;
    const {onSendCaptcha = phone => {}} = this.props;
    if (isSend) {
      return;
    }
    const phone = validatePhone(this.state.phone, region);
    if (!phone) {
      return;
    }
    onSendCaptcha(`+${region.code}-${phone}`);
    this.runTimer();
  };

  runTimer = () => {
    this.setState({isSend: true});
    this.timer = setInterval(() => {
      const {second} = this.state;
      if (second <= 0) {
        this.setState({second: this.count, isSend: false});
        clearInterval(this.timer);
      } else {
        this.setState({second: this.state.second - 1});
      }
    }, 1000);
  };

  renderRightView = () => {
    const {second, isSend, phone, region} = this.state;
    const {title: {sendText = '获取验证码'} = {}} = this.props;

    const checkPhone = !validatePhone(phone, region, false);
    return (
      <TouchableOpacity onPress={this.onSendCode} style={this.style.mr15}>
        <Text
          style={[
            styles.sendCodeTitle,
            {
              color: checkPhone
                ? styles.themeStyle.minorFontColor
                : styles.themeStyle.primaryColor,
            },
          ]}>
          {isSend ? `${second}s` : sendText}
        </Text>
      </TouchableOpacity>
    );
  };
  renderPhoneCodeLogin = ({phoneCodePlaceholder = '请输入验证码', value}) => (
    <View style={[this.style.inputContainer, this.style.pwdSpace]}>
      <Input
        inputType="phoneCode"
        placeholder={phoneCodePlaceholder}
        onChangeText={this.setCode}
        value={value}
        rightIcon={this.renderRightView()}
        inputContainerStyle={this.style.commonInputContainer}
        inputStyle={[this.style.loginStyle.inputStyle, {paddingLeft: 0}]}
        placeholderTextColor={this.style.themeStyle.minorFontColor}
        selectionColor={this.style.themeStyle.primaryColor}
        defaultValue={this.state.code}
        returnKeyType="done"
        onSubmitEditing={this.phoneCodeRegister}
      />
    </View>
  );

  phoneCodeRegister = async () => {
    const {region} = this.state;
    const phone = validatePhone(this.state.phone, region);
    if (!phone) {
      return;
    }
  };

  render() {
    const {
      phone,
      sendCodeText = '发送验证码',
      phoneText,
      phoneCodePlaceholder,
      onChangePhoneOrEmail,
      titleText,
      showName,
      value,
      ...rest
    } = this.props;
    return (
      <>
        <View style={styles.tabBody}>
          {this.renderInput()}
          <View style={this.style.separatorLine} />
          {this.renderPhoneCodeLogin({phoneCodePlaceholder, value})}
          <View style={this.style.separatorLine} />
          {showName ? (
            <>
              {this.renderNameInput()}
              <View style={this.style.separatorLine} />
            </>
          ) : null}
        </View>
      </>
    );
  }
}

const styles = StyleSheet.create({
  tabBody: {
    marginTop: 40,
  },

  pwdSpace: {
    marginTop: 10,
  },
  mr15: {
    paddingRight: 15,
  },
  themeStyle: {
    primaryColor: '#01987B',
    minorFontColor: '#9BA7B2',
  },
  separatorLine: {
    height: 1,
    backgroundColor: '#eee',
    marginHorizontal: 42,
  },
  loginStyle: {
    inputStyle: {
      paddingLeft: 11,
      paddingVertical: 10,
      fontSize: 16,
    },
  },
  commonInputContainer: {
    borderBottomColor: 'transparent',
  },
  inputContainer: {
    height: 48,
    marginHorizontal: 32,
  },
  sendCodeTitle: {
    fontSize: 14,
    color: '#01987B',
  },
});
